package com.hjm.admin.moule.utils.rxhelper;

import android.content.Intent;
import android.provider.ContactsContract;

import com.allen.library.RxHttpUtils;
import com.allen.library.base.BaseDataObserver;
import com.allen.library.bean.BaseData;
import com.allen.library.utils.ToastUtils;
import com.hjm.admin.moule.MyApp;
import com.hjm.admin.moule.utils.LoadingHelper;
import com.hjm.admin.moule.view.activity.impl.LoginActivity;

import io.reactivex.disposables.Disposable;

public abstract class RxObserver<T> extends BaseDataObserver<T> {
    boolean isLoading;

    public RxObserver() {
    }

    public RxObserver(boolean isLoading) {
        this.isLoading = isLoading;
    }

    protected abstract void onError(String errorMsg);

    protected abstract void onSuccess(T data);

    @Override
    public void doOnSubscribe(Disposable disposable) {
        RxHttpUtils.addDisposable(disposable);
    }

    @Override
    public void doOnError(String s) {
        dismissLoading();
        ToastUtils.showToast(s);
        onError(s);
    }

    @Override
    public void doOnNext(BaseData<T> baseData) {
        switch (baseData.getCode()) {
            case 10000:
                onSuccess(baseData.getData());
                break;
            case 6001:
            case 6002:
                ToastUtils.showToast(baseData.getMsg());
                Intent intent = new Intent(MyApp.getAppContext(), LoginActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                MyApp.getAppContext().startActivity(intent);
                break;
            case 10005:
            case 40000:
            case 40001:
            case 40003:
            case 40004:
            case 40005:
            case 50000:
            case 50003:
                ToastUtils.showToast(baseData.getMsg());
                onError(baseData.getMsg());
                break;
            default:
                onError(baseData.getMsg());
                break;
        }
    }

    @Override
    public void doOnCompleted() {
        dismissLoading();
    }

    private void dismissLoading() {
        if (isLoading) {
            LoadingHelper.getInstance().hideLoading();
        }
    }
}
